<template>
	<view class="container" style="min-height: 100vh;background-color: #fff;display: flex;flex-direction: column;">
		<view class="title-box">
			<text>请填写或上传身份证以验证账号信息</text>
		</view>
		<view class="form-box">
			<view class="form-item">
				<view class="form-item__label">
					姓名
				</view>
				<uni-easyinput v-model="name" @input="init" class="input-content" placeholder="请填写姓名或上传身份证" placeholder-style="font-size: 14px;" :input-border="false"></uni-easyinput>
			</view>
			<view class="form-item">
				<view class="form-item__label">
					身份证号
				</view>
				<uni-easyinput v-model="idcard" @input="init" class="input-content" placeholder="请填写身份证号或上传身份证" placeholder-style="font-size: 14px;" :input-border="false"></uni-easyinput>
			</view>
			<view class="upload-btn" @click="uploadIdcard">
				上传身份证
			</view>
		</view>
		<view class="result-box" v-if="status !== ''">
			<view class="title-box">
				<text>系统信息校验</text>
			</view>
			<view class="result-content">
				<text space="emsp" decode v-if="status === 1">{{''}}&emsp;&emsp;您的身份信息已存在系统账号{{hindMobile(mobile)}}中，请您使用原手机号登录。
				&emsp;&emsp;如您原手机号无法使用，可以通过扫脸认证找回账号并修改登录手机号。
				</text>
				<text space="emsp" decode v-if="status === 0">{{''}}&emsp;&emsp;系统未查询到含您身份信息的账号，请您核对身份信息是否正确或直接通过手机号注册</text>
			</view>
		</view>
		<view class="footer-box">
			<button class="reset-button submit-btn" @click="onConfirmIdcard" v-if="status === ''">确认</button>
			<view v-if="status === 1">
				<button class="reset-button submit-btn" style="margin-bottom: 10px;" @click="goLogin(mobile)">使用原手机号登录</button>
				<button class="reset-button submit-btn" @click="onChangePhone">使用新手机号登录</button>
			</view>
			<button class="reset-button submit-btn" @click="goLogin('')" v-if="status === 0">手机号登录/注册</button>
			<view :style="[{ height: (safeBottomHeight?safeBottomHeight:20) + 'px' }]"></view>
		</view>
		<uni-popup ref="idcardPop" type="bottom" mask-background-color="rgba(0,0,0,0.8)">
			<view class="popup-wrap">
				<view class="popup-describe">
					<image src="../../static/icon_example_idcard01.png" mode="aspectFit"></image>
					<view>
						<view class="title">请上传身份证人像面照片</view>
						<view class="desc">
							<view>保证证件四角可见，无遮挡，无反光；</view>
							<view>姓名、身份证号码等信息清晰，无涂改</view>
						</view>
					</view>
				</view>
				<view class="popup-box">
					<view @click="onCamera('camera')">拍照</view>
					<view @click="onCamera('album')">从相册选择</view>
				</view>
				<view class="popup-cancel" @click="onCancel">取消</view>
			</view>
		</uni-popup>
		<uni-popup ref="changePhonePop" type="center">
			<view class="unipop__ui_body changePhoneBox">
					<view class="unipop__ui_tit">手机号验证码</view>
					<view class="unipop__ui_close" @click="close('changePhonePop')">
						<uni-icons type="closeempty" size="20" color="#aaa"></uni-icons>
					</view>
					<view class="unipop__ui_cnt">
						<view class="cp-tip">
							您正在找回账号并修改登录手机号，请在通过扫脸认证后使用新手机号完成登录。
						</view>
						<view class="cp-tip old-phone">
							原手机号：{{hindMobile(mobile)}}
						</view>
						<view class="form" style="padding-top: 20px;">
							<view class="form-item" style="margin-bottom: 5px;">
								<uni-easyinput v-model="newMobile" maxlength="11" class="input-content" placeholder="请输入新手机号" placeholder-style="font-size: 14px;" :input-border="false"></uni-easyinput>
							</view>
							<view class="form-item">
								<uni-easyinput v-model="code" maxlength="6" class="input-content" placeholder="请输入验证码" placeholder-style="font-size: 14px;" :input-border="false" :clearable="false"></uni-easyinput>
								<button class="reset-button code-btn" @click="getSmsCode('back', newMobile)">{{ smsText }}</button>
							</view>
						</view>
					</view>
					<view class="unipop__ui_btns">
						<button class="reset-button auth-btn" @click="goFaceAuth">前往扫脸认证</button>
					</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import debounce from '@/common/debounce.js'
	import dayjs from 'dayjs';
	export default {
		data() {
			return {
				name: '',
				idcard: '',
				status: '',
				mobile: '',
				message: '',
				code: '',
				lastTimer: 0,
				smsText: '获取验证码',
				newMobile: '',
				safeBottomHeight: uni.getSystemInfoSync().safeAreaInsets.bottom,
			}
		},
		onLoad() {
			this.init()
		},
		async onShow(options) {
			if (uni.getStorageSync(this.DATA_KEY.backAccountFlag)) {
				this.runNum = 0
				this.isResult = false
				uni.setStorageSync(this.DATA_KEY.backAccountFlag, false);
				await this.updateFaceVerifyOrderNumber(this.orderNumber)
				uni.showLoading({
					title: '加载中...'
				})
				// this.checkPlatformDriver()
				this.runGet()
			}
		},
		methods: {
			init() {
				this.status = '';
				this.mobile = '';
				this.message = '';
				this.code = '';
				this.lastTimer = 0;
				this.smsText = '获取验证码';
				this.newMobile = '';
			},
			runGet() {
				this.checkPlatformDriver()
				setTimeout(() => {
					this.runNum++
					if (this.runNum < 3 && !this.isResult) {
						this.runGet()
					}
				},2000)
			},
			uploadIdcard() {
				this.$refs['idcardPop'].open()
			},
			onCamera(type) {
				this.$refs['idcardPop'].close()
				uni.chooseImage({
					count: 1,
					sourceType: [type],
					sizeType: 'compressed',
					success: res => {
						console.log('ddd======1------------>', res.tempFiles);
						console.log('ddd======2------------>', res.tempFiles[0]);
						console.log('ddd======3------------>', res.tempFiles[0].size);
						let resSize = res.tempFiles[0].size;
						if (resSize > 10485760) {
							uni.showToast({
								title: '上传的图片大小不超过10M,请重新上传！',
								icon: 'none',
								duration: 2000,
								mask: true
							});
							return;
						}
						uni.showLoading({
							title: '上传中'
						});
							uni.uploadFile({
								url: `${this.API}/driverService/uploadIdcard`,
								fileType: 'image',
								name: 'file',
								filePath: res.tempFilePaths[0],
								file: res.tempFiles,
								header: {
									'Content-Type': 'multipart/form-data;boundary=ebf9f03029db4c2799ae16b5428b06bds',
									Authorization: uni.getStorageSync(this.DATA_KEY.token)
								},
								formData: {
									fileType: '2',
									// mobile: this.userInfo.mobile,
									fileId: Math.floor(Math.random() * 1259),
									ocrOrNot: '1',
									orderId: ''
								},
								success: res => {
									uni.hideLoading();
									let data = JSON.parse(res.data);
									if (data.code == 0) {
										this.init()
										this.idcard = data.data.id;
										this.name = data.data.name;
									} else {
										uni.showToast({
											title: JSON.parse(res.data).msg,
											icon: 'none'
										});
									}
								},
								fail: error => {
									uni.showToast({
										title: '文件上传失败',
										icon: 'none'
									});
								}
							});
						},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			onCancel() {
				this.$refs['idcardPop'].close()
			},
			onConfirmIdcard() {
				if (!this.name) {
					uni.showToast({
						title: "请填写姓名",
						icon: "none"
					})
					return false
				}
				let regName = /^[a-zA-Z\u4E00-\u9FA5]+(([a-zA-Z]+\s[a-zA-Z]+)|([\u4E00-\u9FA5]+([•]{1}[\u4E00-\u9FA5]+)*))*$/
				if (!regName.test(this.name)) {
					uni.showToast({
						title: "请填写正确的姓名",
						icon: "none"
					})
					return false
				}
				if (!this.idcard) {
					uni.showToast({
						title: "请填写身份证号",
						icon: "none"
					})
					return false
				}
				let regIdcard = /^\d{15}$|^\d{17}[\d|x]/
				if (!regIdcard.test(this.idcard)) {
					uni.showToast({
						title: "请填写正确的身份证号",
						icon: "none"
					})
					return false
				}
				this.getResult()
			},
			getResult() {
				this.wxRequest({
					url: `${this.API}/driverService/checkIdCard`,
					method: 'POST',
					data: {
						idcard: this.idcard
					},
					title: '加载中...',
					success: res => {
						console.log(res)
						if (res.data.code == 0) {
							this.status = res.data.data.status
							this.mobile = res.data.data.mobile
							this.message = res.data.data.message
						}
					}
				});
			},
			onChangePhone() {
				this.$refs['changePhonePop'].open()
			},
			// 发送短信验证码  60秒
			getSmsCode(event, mobile) {
			  let lastSendTimer = this.lastTimer;
			
			  let duration = dayjs().unix() - lastSendTimer;
			  let canSend = duration >= 60;
			
			  if (!canSend) {
					uni.showToast({
						title: '请稍后再试',
						icon: 'none'
					})
			    return;
			  }
				var reg = /^1[3456789]\d{9}$/;
			  if (!reg.test(mobile)) {
					uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					})
			    return;
			  }
				// this.lastTimer = dayjs().unix();
				// this.getSmsTimer()
				this.wxRequest({
					url: `${this.API}/miniApp/auth/sms-code-tel?tel=` + mobile,
					method: 'GET',
					title: '验证码发送中...',
					success: res => {
						if (res.data.code == 0) {
							uni.showToast({
								title: '验证码已发送',
								icon: 'none'
							});
							this.lastTimer = dayjs().unix();
							this.getSmsTimer()
						}
					}
				});
			
			},
			getSmsTimer(event) {
			  let lastSendTimer = this.lastTimer;
			
			  let duration = dayjs().unix() - lastSendTimer - 60;
			  let canSend = duration >= 0;
			  if (canSend) {
			    this.smsText = '获取验证码';
			  }
			
			  if (!canSend) {
			    setTimeout(() => {
			      duration++;
						this.getSmsTimer(event)
			    }, 1000);
			    this.smsText = -duration.toString() + ' 秒';
			  }
			},
			goFaceAuth(mobile) {
				var reg = /^1[3456789]\d{9}$/;
				if (!reg.test(this.newMobile)) {
					uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					})
				  return;
				}
				if (!this.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					})
				  return;
				}
				debounce(async ()=>{
					const result1 = await this.smsAuthentication();
					const result2 = await this.getDriverIdCard();
					this.accessToken = result2.data.accessToken;
					const result3 = await this.getFaceQRCode(result2.data);
					let orderNumber = result3.data.orderNumber;
					this.orderNumber = orderNumber
					// const result4 = await this.updateFaceVerifyOrderNumber(orderNumber);
					let that = this
					// #ifdef APP-PLUS
					uni.showModal({
						title: '提示',
						content: '是否去进行实名认证?跳转进行实名认证后需要重新打开当前APP!',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								that.close('changePhonePop');
								uni.setStorageSync(that.DATA_KEY.backAccountFlag, true);
								plus.share.getServices(
									function(res) {
										var sweixin = null;
										console.log(res);
										for (var i = 0; i < res.length; i++) {
											var t = res[i];
											console.log(t);
											if (t.id == 'weixin') {
												sweixin = t;
											}
										}
										if (sweixin) {
											console.log('dddd=', 'a=' + sweixin + '=b');
											sweixin.launchMiniProgram({
												// id: 'gh_cec8224b00da',
												id: 'gh_45eec401ff1c',
												type: 0, //0-正式版 1.测试版，2，体验版
												path: 'pages/verify/info/index?id=' + orderNumber
											});
										}
									},
									function(res) {
										console.log(JSON.stringify(res));
									}
								);
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					// #endif
					
					// #ifdef MP-WEIXIN
					uni.showModal({
						title: '提示',
						content: '是否去进行实名认证?',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								that.close('changePhonePop');
								//uni.navigateToMiniProgram  打开另一个小程序
								uni.navigateToMiniProgram({
									// appId: 'wxfd2861dc1c86b3a0',
									appId: 'wxfc1e27e05fdd062b',
									path: 'pages/verify/info/index?id=' + orderNumber,
									envVersion: 'release',
									success(res) {
										uni.setStorageSync(that.DATA_KEY.backAccountFlag, true);
										console.log('跳转成功');
									},
									fail(res) {
										console.log('跳转失败' + JSON.stringify(res));
									}
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					// #endif
				},3000,true)
				// uni.navigateTo({
				// 	url: '/pages/account/resutl'
				// })
			},
			smsAuthentication() {
				return new Promise((resolve, reject) => {
					this.wxRequest({
						url: `${this.API}/driverService/smsAuthentication`,
						method: 'POST',
						data: {
							tel: this.newMobile,
							code: this.code
						},
						title: '加载中...',
						success: (res => {
							if (res.data.code == 0) {
								resolve(res.data)
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
								resolve(false)
							}
						}),
						fail: (err => {
							reject(err)
						})
					})
				})
			},
			getDriverIdCard() {
				return new Promise((resolve, reject) => {
					let that = this
					this.wxRequest({
						url: `${that.API}/driverService/getDriverIdCard?idcard=${that.idcard}&mobile=${that.mobile}`,
						method: 'GET',
						data: {
							idcard: that.idcard,
							mobile: that.mobile,
						},
						title: '加载中...',
						success: (res => {
							if (res.data.code == 0) {
								resolve(res.data)
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
								resolve(false)
							}
						}),
						fail: (err => {
							reject(err)
						})
					})
				})
			},
			getFaceQRCode(data) {
				return new Promise((resolve, reject) => {
					let that = this
					this.wxRequest({
						url: `${that.API2}/api/face/getFaceQRCode?access_token=` + data.accessToken,
						method: 'POST',
						data: {
							companyTaxNumber: data.taxNumber,
							realName: data.driverName,
							idCard: data.idcard,
							idPhotoUp: data.idcard1Base64,
							idPhotoDown: data.idcard2Base64,
							callbackUrl: `${that.API}/driverService/isLivingBodyState`
						},
						title: '加载中...',
						success: (res => {
							if (res.data.code == 0) {
								resolve(res.data)
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
								resolve(false)
							}
						}),
						fail: (err => {
							reject(err)
						})
					})
				})
			},
			updateFaceVerifyOrderNumber(orderNumber) {
				return new Promise((resolve, reject) => {
					let that = this
					this.wxRequest({
						url: `${that.API}/driverService/updateFaceVerifyOrderNumber`,
						method: 'POST',
						data: {
							idcard: that.idcard,
							mobile: that.mobile,
							orderNumber: orderNumber,
							accessToken: that.accessToken
						},
						title: '加载中...',
						success: (res => {
							if (res.data.code == 0) {
								resolve(res.data)
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
								resolve(false)
							}
						}),
						fail: (err => {
							reject(err)
						})
					})
				})
			},
			checkPlatformDriver() {
				let that = this
				this.wxRequest({
					url: `${that.API}/driverService/checkPlatformDriver?idcard=${that.idcard}&mobile=${that.mobile}`,
					method: 'GET',
					data: {
						idcard: that.idcard,
						mobile: that.mobile,
					},
					success: res => {
						if (res.data.code == 0) {
							this.type = 'success';
							this.isResult = true
							this.updateDriverTel()
							uni.hideLoading()
							uni.navigateTo({
								url: '/pages/account/resutl?type=success&tel='+that.newMobile,
								success() {
									that.init()
								}
							})
						} else {
							if (this.runNum == 2) {
								this.type = 'fail';
								this.isResult = true
								uni.hideLoading()
								uni.navigateTo({
									url: '/pages/account/resutl?type=fail&id='+that.orderNumber,
									success() {
										that.init()
									}
								})
							}
						}
					},
				})
			},
			updateDriverTel() {
				this.wxRequest({
					url: `${this.API}/driverService/updateDriverTel`,
					method: 'POST',
					data: {
						tel: this.newMobile,
						mobile: this.mobile,
						mod: 2
					},
					success: (res => {
						console.log('修改成功')
					})
				})
			},
			goLogin(mobile) {
				uni.navigateTo({
					url: '/pages/personal/login',
					success(res) {
						mobile && res.eventChannel.emit('login', { phone: mobile })
					}
				})
			},
			close(name) {
				this.$refs[name].close()
			},
			hindMobile(val) {
				if (val && typeof val === 'string') {
					var reg = /^(\d{3})\d*(\d{4})$/;
					return val.replace(reg,'$1****$2')
				}
			}
		},
		onUnload() {
			if(uni.getStorageSync(this.DATA_KEY.backAccountFlag)){
				uni.setStorageSync(this.DATA_KEY.backAccountFlag, false);
			}
		},
	}
</script>

<style lang="scss">
$color-primary: #2B7CFF;
.reset-button {
	  padding: 0;
	  margin: 0;
	  font-size: inherit;
	  background-color: transparent;
	  color: inherit;
	  position: relative;
	  border: 0rpx;
	  /* #ifndef APP-NVUE */
	  display: flex;
	  /* #endif */
	  align-items: center;
	  justify-content: center;
	  box-sizing: border-box;
	  text-align: center;
	  text-decoration: none;
	  white-space: nowrap;
	  vertical-align: baseline;
	  transform: translate(0, 0);
	}
	.reset-button.button-hover {
	  transform: translate(1px, 1px);
	  background: none;
	}
	
	.reset-button::after {
	  border: none;
	}
	.result-content {
		padding: 0 30rpx;
		font-size: 26rpx;
		color: #333;
	}
.title-box {
	font-size: 28rpx;
	color: #000;
	font-weight: 600;
	position: relative;
	display: flex;
	align-items: center;
	padding-left: 40rpx;
	margin: 30rpx 0;
}
.title-box::before {
	content: " ";
	width: 8rpx;
	height: 1.2em;
	position: absolute;
	left: 20rpx;
	background-color: $color-primary;
}
.form-box {
	padding: 30rpx;
}
.form-item {
	display: flex;
	align-items: center;
	position: relative;
	margin-bottom: 20rpx;
	&:last-child {
		margin-bottom: 0;
	}
	&::after {
		content: " ";
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 1px;
		border-bottom: .5px solid #e5e5e5;
	}
	&__label {
		width: 5em;
		font-size: 28rpx;
	}
	.input-content {
		font-size: 28rpx;
	}
	
}
.upload-btn {
	font-size: 28rpx;
	color: $color-primary;
	display: inline-block;
}
.popup-wrap{
		// padding: 0 24rpx calc(24rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx calc(24rpx);
		color: #007aff;
		text-align: center;
		background: transparent;
		.popup-describe{
			color: #fff;
			position: absolute;
			top: -55vh;
			left: 50%;
			transform: translate(-50%, 0);
			.title{
				margin: 24rpx 0;
				font-size: 36rpx;
			}
			.desc{
				font-size: 24rpx;
			}
		}
		.popup-box{
			background: #fff;
			margin-bottom: 24rpx;
			border-radius: 8rpx;
			view{
				padding: 24rpx 0;
				&:first-child{
					border-bottom: 1rpx solid #f9f9f9;
				}
			}
		}
		.popup-cancel{
			background: #fff;
			padding: 24rpx 0;
			border-radius: 8rpx;
		}
	}
	.footer-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 30rpx;
		padding-bottom: 0;
		box-sizing: border-box;
		.submit-btn {
			background-color: $color-primary;
			color: #fff;
			&.button-hover {
				background: rgba(43, 124, 255, .9);
			}
		}
	}
	
	.unipop__ui_body {
		background-color: #fff;
		border-radius: 12px;
		text-align: center;
		position: relative;
	}
	@media screen and (min-width: 352px) {
		.unipop__ui_body {
			width: 320px;
		}
	}
	
	.unipop__ui_tit {
		padding: 32px 24px 16px;
		font-size: 17px;
		color: rgba(0, 0, 0, 0.9);
		font-weight: 700;
		font-size: 17px;
		line-height: 1.4;
		position: relative;
	}
	.unipop__ui_close {
		position: absolute;
		right: 15px;
		top: 15px;
		
	}
	.unipop__ui_cnt {
		padding: 0 24px;
		margin-bottom: 32px;
		font-size: 17px;
		line-height: 1.4;
		word-wrap: break-word;
		color: rgba(0, 0, 0, 0.5);
	}
	.unipop__ui_btns {
		display: flex;
		position: relative;
	}
	.unipop__ui_btns::after {
		content: " ";
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		height: 1px;
		border-top: 1px solid rgba(0,0,0,0.1);
		color: rgba(0,0,0,0.1);
		transform-origin: 0 0;
		transform: scaleY(0.5);
	}
	// .unipop__ui_btns .btn {
	// 	flex: 1;
	// 	font-size: 17px;
	// 	line-height: 1.4;
	// 	font-weight: 600;
	// 	color: #576b95;
	// 	padding: 16px 23px;
	// 	user-select: none;
	// 	position: relative;
	// }
	// .unipop__ui_btns .btn.btn-default {
	// 	color: rgba(0, 0, 0, 0.9);
	// }
	// .unipop__ui_btns .btn:first-child::after {
	// 	display: none;
	// }
	// .unipop__ui_btns .btn::after {
	// 	content: " ";
	// 	position: absolute;
	// 	left: 0;
	// 	top: 0;
	// 	width: 1px;
	// 	bottom: 0;
	// 	border-left: 1px solid rgba(0,0,0,0.1);
	// 	color: rgba(0,0,0,0.1);
	// 	transform-origin: 0 0;
	// 	transform: scaleX(0.5);
	// }
	
	.cp-tip {
		color: #333;
		font-size: 15px;
		&.old-phone {
			text-align: left;
			padding-top: 20px;
		}
	}
	.code-btn {
		background-color: $color-primary;
		color: #fff;
		font-size: 12px;
		height: 28px;
		width: 80px;
		padding: 0 10px;
	}
	.auth-btn {
		background-color: $color-primary;
		color: #fff;
		margin: 10px auto;
		padding: 0 20px;
	}
	.changePhoneBox .uni-easyinput__content-input {
		padding-left: 0 !important;
	}
	.safH {
	}
</style>
